package cn.yj.syslog.aspect.pageview;

import cn.yj.commons.utils.HttpHeaderUtil;
import cn.yj.syslog.aspect.OncePleaseOne;
import cn.yj.syslog.entity.PageView;
import cn.yj.syslog.entity.SysLog;
import cn.yj.syslog.service.IPageViewService;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-12-17 17:34
 */
public class PageViewLogMethodInterceptor extends OncePleaseOne {

    private static final Logger log = LoggerFactory.getLogger(PageViewLogMethodInterceptor.class);

    private IPageViewService iPageViewService;

    public PageViewLogMethodInterceptor(IPageViewService iPageViewService) {
        this.iPageViewService = iPageViewService;
    }


    private final ExecutorService executorService = Executors.newFixedThreadPool(10);

    @Override
    public Object doInvoke(MethodInvocation methodInvocation, HttpServletRequest request) throws Throwable {
        executorService.execute(()->saveVisit(request));
        return methodInvocation.proceed();
    }

    private void saveVisit(HttpServletRequest request) {
        try {
            PageView pageView = new PageView();
            pageView.setIp(HttpHeaderUtil.getIpAddr(request));
            Object device = request.getAttribute("device");
            String from = device != null? device.toString() : "未知";
            if (SysLog.APP.equals(from)) {
                executorService.execute(() -> iPageViewService.save(pageView));
            }
        } catch (Exception e) {
            log.error("处理访问日志异常");
            e.printStackTrace();
        }
    }
}
